/**
 * ApplicationContextHolder.java - 2012-2-16
 *
 * Licensed Property to China UnionPay Co., Ltd.
 * 
 * (C) Copyright of China UnionPay Co., Ltd. 2010
 *     All Rights Reserved.
 *
 * Project Info: China UnionPay Internet Acquiring Project
 * 
 * Modification History:
 * =============================================================================
 *   Author         Date          Description
 *   ------------ ---------- ---------------------------------------------------
 *        
 * =============================================================================
 */
package com.lijin.batchsys.framework.common;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Description:  Spring Application Context的持有类
 *
 * (C) Copyright of China UnionPay Co., Ltd. 2010.
 *
 */
public class ApplicationContextHolder implements ApplicationContextAware {

	private final static Logger logger = Logger.getLogger(ApplicationContextHolder.class);
	
	private static ApplicationContext context = null;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		if (applicationContext != null) {
			context = applicationContext;
			logger.info("Spring上下文初始化完成");
		}
	}
	
	public static void init(ApplicationContext applicationContext) {
		if (context == null) {
			context = applicationContext;
		}
	}
	
	/**
	 * 根据Bean名称获取相应的Bean
	 * @param <T>
	 * @param beanName
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String beanName) {
		if (context == null) {
			throw new IllegalStateException("Spring上下文未初始化");
		}
		return (T) context.getBean(beanName);
	}

}
